package com.atguigu.chapter11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Session;
import org.apache.flink.table.api.SessionWithGapOnTimeWithAlias;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;
import java.time.ZoneOffset;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/24 10:03
 */
public class Flink10_Table_Window_Grouped {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        tenv.getConfig().setLocalTimeZone(ZoneOffset.ofHours(0));
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env
            .fromElements(new WaterSensor("sensor_1", 1000L, 10),
                          new WaterSensor("sensor_1", 2000L, 20),
                          new WaterSensor("sensor_1", 4000L, 40),
                          new WaterSensor("sensor_1", 5000L, 50)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
            );
        
        Table table = tenv.fromDataStream(waterSensorStream, $("id"), $("ts").rowtime().as("et"), $("vc"));
        // 每2s统计最近2s每个传感器的水位和
        //        TumbleWithSizeOnTimeWithAlias w = Tumble.over(Expressions.lit(2).second()).on($("et")).as("w");
        //        SlideWithSizeAndSlideOnTimeWithAlias w = Slide.over(lit(5).second()).every(lit(2).second()).on($("et")).as("w");
        SessionWithGapOnTimeWithAlias w = Session.withGap(lit(2).second()).on($("et")).as("w");
        
        table
            .window(w)
            .groupBy($("w"), $("id"))
            .select($("w").start().as("w_start"), $("w").end().as("w_end"), $("id"), $("vc").sum().as("vc_sum"))
            .execute()
            .print();
        
    }
}
